﻿Imports MICROFORMA.BLL
Imports MICROFORMA.BEL

Public Class frmListsAdd
    Public bolUpdate As Boolean
    Public idLista As Int16
    Dim dtableLista As DataTable ' = listasBL.List(idLista)
    Dim listasBL As ListasBL
    Dim datoExternoBL As DatosExternosBL
    Dim strText As String = ""

    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        Call ShowStringCollection()
    End Sub

    Private Sub ShowStringCollection(Optional ByVal itemString As String = "")

        Dim _frmCollectionString As New frmCollectionString(itemString)
        _frmCollectionString.ShowDialog()
        strText = _frmCollectionString.txtItems.Text
        _frmCollectionString.Dispose()

        Call AddItemCheckedList(strText)
    End Sub

    Private Sub AddItemCheckedList(ByVal stringText As String)
        If strText.Length > 0 Then
            Dim a As String()
            chkListBoxLists.Items.Clear()
            a = Split(stringText.Trim, vbNewLine)
            chkListBoxLists.Items.AddRange(a)
        End If
    End Sub

    Private Function ReplaceItemsContent(ByVal stringText As String) As String
        Return Replace(stringText, vbNewLine, " ")
    End Function

    Private Function UnReplaceItemsContent(ByVal stringText As String) As String
        Return Replace(stringText, " ", vbNewLine)
    End Function

    Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
        If chkListBoxLists.Items.Count > 0 Then
            Call ShowStringCollection(getStringCollectionChkList())
        End If
    End Sub

    Private Function getStringCollectionChkList() As String 'Optional ByVal itemCount As Integer = 0
        Dim r(chkListBoxLists.Items.Count - 1) As String

        For i As Int32 = 0 To chkListBoxLists.Items.Count - 1
            r(i) = chkListBoxLists.Items(i).ToString
        Next

        Dim s As String = String.Join(vbNewLine, r)

        Return s

    End Function

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        If chkListBoxLists.CheckedItems.Count > 0 Then
            Call DeleteItemsChlList()
            Call AddItemCheckedList(strText)
        End If
    End Sub

    Private Sub DeleteItemsChlList()
        Dim i As Integer

        For i = chkListBoxLists.Items.Count - 1 To 0 Step -1
            If chkListBoxLists.GetItemCheckState(i) = CheckState.Checked Then
                chkListBoxLists.Items.RemoveAt(i)
            End If
        Next

        strText = getStringCollectionChkList()

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub frmListsAdd_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If bolUpdate Then
            Me.Text = "Actualizar Lista"
            dtableLista = listasBL.List(idLista)
            Call LoadChkLists()
            Call LoadComboNamesConnections()
            Call LoadComboFather()
            Call LoadCombos(dtableLista)
        Else
            Me.Text = "Agregar Lista"
            dtableLista = listasBL.List()
        End If


    End Sub

    Private Sub LoadChkLists()

        For Each dtrFila As DataRow In dtableLista.Rows

            txtNameList.Text = dtrFila("Nombre")
            rdbListsDI.Checked = IIf(Convert.ToBoolean(dtrFila("ListaInterna")), True, False)
            rdbListsDE.Checked = IIf(Convert.ToBoolean(dtrFila("ListaInterna")), False, True)
            strText = UnReplaceItemsContent(dtrFila("Contenido"))
            Call AddItemCheckedList(strText)

            If rdbListsDE.Checked Then
                cboNameConexion.SelectedValue = dtrFila("IdDatoExterno")
                cboDataMember.SelectedText = dtrFila("CampoMostrar")
                cboDataValue.SelectedText = dtrFila("CodigoInterno")
                'strText = dtrFila("Contenido")
                'chkListBoxLists.Text = Split(dtrFila("Contenido"), " ").ToString
                cboListFather.SelectedValue = dtrFila("ListaPadre")
                cboListsFatherRelation.SelectedValue = dtrFila("CampoRelacionPadre")
            End If

        Next
        listasBL = Nothing

    End Sub

    Private Sub LoadComboNamesConnections()
        datoExternoBL = New DatosExternosBL

        cboNameConexion.DataSource = datoExternoBL.getList
        cboNameConexion.ValueMember = "IdDatoExterno"
        cboNameConexion.DisplayMember = "CadenaConexion"
    End Sub

    Private Sub LoadComboFather()
        listasBL = New ListasBL
        Dim table As DataTable = listasBL.List

        cboListFather.ValueMember = "IdLista"
        cboListFather.DisplayMember = "Nombre"

        Dim dRow As DataRow
        dRow = table.NewRow
        dRow("IdLista") = 0
        dRow("Nombre") = "[ Seleccione ]"

        table.Rows.Add(dRow)
        table.DefaultView.Sort = "IdLista"

        cboListFather.DataSource = table

        'Dim listasBL As New ListasBL
        'Dim table As DataTable = listasBL.List

        'cboList.ValueMember = "IdLista"
        'cboList.DisplayMember = "Nombre"

        'Dim dRow As DataRow
        'dRow = table.NewRow
        'dRow("IdLista") = 0
        'dRow("Nombre") = "[ Seleccione ]"

        'table.Rows.Add(dRow)
        'table.DefaultView.Sort = "IdLista"
        'cboList.DataSource = table

    End Sub

    Private Sub btnTestQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestQuery.Click
        If ValidaTestQuery() Then
            Dim dtableQuery As DataTable
            listasBL = New ListasBL
            dtableQuery = listasBL.TestQuery(cboNameConexion.Text, txtQuerySql.Text)

            If Not dtableQuery Is Nothing Then
                Call LoadCombos(dtableQuery)
                Call MessageMistake("Prueba Efectuada Correctamente... !!!", True)
            Else
                Call MessageMistake("La Prueba se realizo sin exito... !!!")
            End If
        End If
    End Sub

    Private Sub LoadCombos(ByVal dtable As DataTable)

        Call DeleteItemsCombos()

        Dim index As Int16 = 1

        cboDataValue.Items.Insert(0, "[ Seleccione ]")
        cboDataMember.Items.Insert(0, "[ Seleccione ]")
        cboListsFatherRelation.Items.Insert(0, "[ Seleccione ]")

        For Each fila As DataColumn In dtable.Columns
            cboDataValue.Items.Insert(index, fila.ColumnName)
            cboDataMember.Items.Insert(index, fila.ColumnName)
            cboListsFatherRelation.Items.Insert(index, fila.ColumnName)
            index = index + 1
        Next

        cboDataValue.SelectedIndex = 0
        cboDataMember.SelectedIndex = 0
        cboListsFatherRelation.SelectedIndex = 0
    End Sub

    Private Sub DeleteItemsCombos()
        cboDataMember.Items.Clear()
        cboDataValue.Items.Clear()
        cboListsFatherRelation.Items.Clear()
    End Sub


    Function ValidaTestQuery() As Boolean

        If cboNameConexion.SelectedIndex <> 0 Then
            MessageMistake("Por favor seleccione un tipo de conexion del listado.")
            cboNameConexion.Focus()
            Exit Function
        End If

        If Trim(txtQuerySql.Text) = "" Then
            MessageMistake("Por favor ingrese la sentencia para efectuar la consulta respectiva.")
            txtQuerySql.Focus()
            Exit Function
        End If

        ValidaTestQuery = True

    End Function

    Private Function SetEntity(Optional ByVal estado As String = "") As ListasBE
        'ReplaceItemsContent()

        Dim listasBE As New ListasBE
        listasBE.Nombre = txtNameList.Text
        listasBE.Contenido = Trim(ReplaceItemsContent(strText))
        listasBE.Estado = estado
        listasBE.ListaInterna = IIf(Me.rdbListsDI.Checked, True, False)

        If Not rdbListsDI.Checked Then
            listasBE.IdDatoExterno = CType(cboNameConexion.SelectedValue, Integer)
            listasBE.SqlSelect = txtQuerySql.Text
            listasBE.ListaPadre = cboListFather.SelectedValue
            listasBE.CampoRelacionPadre = cboListsFatherRelation.SelectedValue 'PREGUNTAR SI ES Int o String
            listasBE.CodigoInterno = cboDataValue.Text
            listasBE.CampoMostrar = cboDataMember.Text
        End If

        If bolUpdate Then
            listasBE.IdLista = idLista
        End If

        Return listasBE

    End Function

    Private Sub rdbListsDE_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbListsDE.CheckedChanged
        If rdbListsDE.Checked Then
            Call EnableButtons(False)
            Me.TabControl1.SelectedTab = Me.TabPageDatosExternos
            Me.TabPageDatosExternos.Focus()
            Call LoadComboNamesConnections()
            Call LoadComboFather()
        End If
    End Sub

    Private Sub rdbListsDI_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbListsDI.CheckedChanged
        If rdbListsDI.Checked Then
            Call EnableButtons(True)
        End If
    End Sub

    Private Sub EnableButtons(Optional ByVal flag As Boolean = Nothing)
        btnNew.Enabled = flag
        btnRename.Enabled = flag
        btnDelete.Enabled = flag
        'txtContenido.BackColor = Color.DarkGray
    End Sub

    Private Sub btnAcept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAcept.Click
        If ValidateForm() Then
            Dim msj As String

            If bolUpdate Then
                msj = EditList(SetEntity("0"))
            Else
                msj = AddList(SetEntity("0"))
            End If

            If msj = "OK" Then
                Call MessageMistake("La operacion se realizo con exito.", True)
            End If
        End If
    End Sub

    Private Function AddList(ByVal listaBE As ListasBE) As String
        Return listasBL.Add(listaBE, listaBE.ListaInterna)
    End Function

    Private Function EditList(ByVal listaBE As ListasBE) As String
        Return listasBL.Edit(listaBE)
    End Function

    Private Function ValidateForm() As Boolean
        If rdbListsDI.Checked Then
            If Not ValidateListInternal() Then
                Exit Function
            End If
        End If

        If rdbListsDE.Checked Then
            'If Not ValidateListInternal() Then
            '    Exit Function
            'End If
            If Trim(txtNameList.Text) = "" Then
                MessageMistake("Por favor Digite el nombre para la lista.")
                txtNameList.Focus()
                Exit Function
            End If
            If cboNameConexion.SelectedIndex < 0 Then
                MessageMistake("Por Seleccione una conexion de la lista de conexiones externas.")
                Me.TabControl1.SelectedTab = TabPageDatosExternos
                cboNameConexion.Focus()
                Exit Function
            End If
            If Trim(txtQuerySql.Text) = "" Then
                MessageMistake("Por favor ingrese la consulta a realizar.")
                Me.TabControl1.SelectedTab = TabPageDatosExternos
                txtQuerySql.Focus()
            End If
            If cboDataMember.SelectedIndex = 0 Then
                MessageMistake("Por Seleccione un item para el nombre del campo del listado.")
                Me.TabControl1.SelectedTab = TabPageDatosExternos
                cboDataMember.Focus()
                Exit Function
            End If
            If cboDataValue.SelectedIndex = 0 Then
                MessageMistake("Por Seleccione un item para el campo de código del listado.")
                Me.TabControl1.SelectedTab = TabPageDatosExternos
                cboDataValue.Focus()
                Exit Function
            End If
            If cboListFather.SelectedIndex = 0 Then
                MessageMistake("Por Seleccione un nombre del Listado de listas.")
                Me.TabControl1.SelectedTab = TabPageJerarquias
                cboListFather.Focus()
                Exit Function
            End If
            If cboListsFatherRelation.SelectedIndex = 0 Then
                MessageMistake("Por Seleccione un nombre del campo que desea relacionar a la lista seleccionada.")
                Me.TabControl1.SelectedTab = TabPageJerarquias
                cboListsFatherRelation.Focus()
                Exit Function
            End If
        End If

        ValidateForm = True
    End Function

    Private Function ValidateListInternal() As Boolean
        If Trim(txtNameList.Text) = "" Then
            MessageMistake("Por favor Digite el nombre para la lista.")
            txtNameList.Focus()
            Exit Function
        End If
        If chkListBoxLists.Items.Count = 0 Then
            MessageMistake("Por favor ingrese el contenido para la lista.")
            btnAcept.Focus()
            Exit Function
        End If
        ValidateListInternal = True
    End Function

    Sub New()
        listasBL = New ListasBL
        InitializeComponent()
    End Sub


End Class